﻿using System;
using System.Linq;
using System.Web.UI.HtmlControls;
using log4net;

namespace TemplateFoundation.Handlers.JavaScriptTranslate
{
    /// <summary>
    /// Used to rewrite JavaScript links in the head element to append language querystring parameter used for translations
    /// </summary>
    /// <remarks>This is used together with the ScriptLanguageInjectorHandler to serve JavaScripts with dynamically generated translation JSON objects</remarks>
    /// <seealso cref="TemplateFoundation.Handlers.JavaScriptTranslate.ScriptLanguageInjectorHandler"/>
    public static class ScriptLinkRewriter
    {
        private static readonly ILog _logger = LogManager.GetLogger(typeof (ScriptLinkRewriter));

        /// <summary>
        /// Adds a JavaScript link for the specified language, or updates an existing JavaScript link to append a language querystring parameter
        /// </summary>
        public static void AddOrUpdateLanguageSpecificJavaScriptLink(this HtmlHead head, string scriptFilePath, string language)
        {
            if (head == null)
            {
                _logger.Error("An HtmlHead object must be specified for which JavaScript links should be added or updated");

                return;
            }

            if (string.IsNullOrWhiteSpace(language))
            {
                _logger.Error("No language code specified for JavaScript links");

                return;
            }

            if (string.IsNullOrWhiteSpace(scriptFilePath))
            {
                _logger.Error("No JavaScript file path specified");

                return;
            }

            var scriptElements = head.Controls
                .OfType<HtmlGenericControl>()
                .Where(
                    c =>
                    c.TagName == "script" && c.Attributes["src"] != null &&
                    c.Attributes["src"].Equals(scriptFilePath, StringComparison.OrdinalIgnoreCase))
                .ToList();

            if (!scriptElements.Any()) // Main JavaScript file not linked
            {
                _logger.DebugFormat("Adding JavaScript link: {0}", scriptFilePath);

                var scriptElement = new HtmlGenericControl("script");
                scriptElement.Attributes.Add("type", "text/javscript");
                scriptElement.Attributes.Add("src", string.Format("{0}?epslanguage={1}", scriptFilePath, language));
                head.Controls.Add(scriptElement);
            }
            else
            {
                if (scriptElements.Count>1)
                {
                    _logger.ErrorFormat("More than one main JavaScript file linked using path: {0}", scriptFilePath);

                    return;
                }

                var updatedFilePath = string.Format("{0}?epslanguage={1}", scriptFilePath, language);

                scriptElements.First().Attributes["src"] = updatedFilePath;

                _logger.DebugFormat("Updated JavaScript link to include language parameter: {0}", updatedFilePath);
            }        
        }
    }
}
